﻿using System;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Interop;
using IWin32Window = System.Windows.Forms.IWin32Window;
using TextBox = System.Windows.Controls.TextBox;
using UserControl = System.Windows.Controls.UserControl;

namespace WpfAdvControls.Dialogs
{
    /// <summary>
    ///     Interaction logic for FolderSelector.xaml
    /// </summary>
    public partial class FolderSelector : UserControl
    {
        /// <summary>
        ///     FolderProperty field back of Folder property
        /// </summary>
        public static readonly DependencyProperty FolderProperty =
            DependencyProperty.Register("Folder", typeof (string), typeof (FolderSelector),
                new UIPropertyMetadata(string.Empty));

        public FolderSelector()
        {
            InitializeComponent();
            folder.DataContext = this;
            folder.SetBinding(TextBox.TextProperty, "Folder");
        }

        /// <summary>
        ///     Folder path
        /// </summary>
        public string Folder
        {
            get { return (string) GetValue(FolderProperty); }
            set { SetValue(FolderProperty, value); }
        }


        /// <summary>
        ///     Click browse button
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">arguments</param>
        private void selectFolder_Click(object sender, RoutedEventArgs e)
        {
            var dlg = new FolderBrowserDialog();
            dlg.SelectedPath = folder.Text;
            dlg.RootFolder = Environment.SpecialFolder.MyComputer;
            var source = PresentationSource.FromVisual(this) as HwndSource;
            IWin32Window win = new OldWindow(source.Handle);
            var result = dlg.ShowDialog(win);
            if (result == DialogResult.OK)
            {
                folder.Text = dlg.SelectedPath;
            }
            dlg.Dispose();
        }
    }
}